package models

import (
	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	ImageId     int64   //图片ID
	Title       string  //标题
	Price       float64 //价格
	Stock       int64   //库存
	GoodsStatus int64   `gorm:"type:int;default:1;comment:默认1 为上架 2为下架"`
}

func (g *Goods) GetGoods(page, pageSize int, sortWord, keyword string) (listGoods []*Goods, err error) {
	query := DB.Model(&Goods{})

	if keyword != "" {
		query = query.Where("title like ?", "%"+keyword+"%")
	}

	if sortWord == "price" {
		query = query.Order("price desc")
	} else if sortWord == "stock" {
		query = query.Order("stock desc")
	} else {
		query = query.Order("created_at desc")
	}

	query = query.Scopes(Paginate(page, pageSize)).
		Find(&listGoods)
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (g *Goods) GetGoodsById(goodsId int64) error {
	return DB.Where("id=?", goodsId).Limit(1).Find(&g).Error
}

//func (g *Goods) CreateGoods() error {
//	return DB.Create(&g).Error
//}
//
//func (g *Goods) UpdateStatus(goodsStatus int64) error {
//	return DB.Model(*g).Update("goods_status", goodsStatus).Error
//}
//
//type Images struct {
//	gorm.Model
//	GoodsId int64  `gorm:"type:int(3);comment:商品ID"`
//	Url     string `gorm:"type:varchar(255);comment:图片地址"`
//}
//
//type Visit struct {
//	gorm.Model
//	GoodsId int64 //商品ID
//	Visits  int64 //浏览量
//}
